/**
 * Created by zhangyida on 15/12/28.
 */
'use strict';
import {
    View,
    Image,
    Text,
    Animated,
    TouchableHighlight,
    AsyncStorage,
    Navigator,
    StyleSheet,
    AlertIOS,
    ActivityIndicator
} from 'react-native';
import React from 'react';
import tcomb from 'tcomb-form-native';
import DeviceInfo from 'react-native-device-info';
import URL from '../config/server';
import {Utils} from '../config/utils';
import {Key} from '../config/key';

//表单验证配置
const Form = tcomb.form.Form;
const User = tcomb.struct({
    username: tcomb.String,
    password: tcomb.String
});


//自定义导航头
const NavigationBarRouteMapper = {
    LeftButton(route, navigator, index, navState) {
        return null;
    },
    RightButton(route, navigator, index, navState) {
        return null;
    },
    Title(route, navigator, index, navState) {
        return (
            <Text style={{color: 'white', margin: 10, fontSize: 20}}>
                登录
            </Text>
        );
    }
};


export default class Login extends React.Component {

    //login组件
    constructor(props) {
        super(props);

        this.state = {
            value: {
                username: props.message==undefined ? '' : props.message.regPhone,
                password: props.message==undefined ? '' : props.message.regPwd,
            },
            options: {
                auto: 'placeholders',
                fields: {
                    username: {
                        placeholder: "手机号\/QQ邮箱\/QQ号"
                    },
                    password: {
                        secureTextEntry:true,
                        // password: true,
                        placeholder: '请输入正确的密码',
                        error: '用户名或密码错误'
                    }
                }
            }
        };
    }

    componentDidMount(){
        
    }

    _openWs() {
        /*创建WebSocket*/
        const WS_URL = URL.WsLocal + Key.username;
        var ws = new WebSocket(WS_URL);

        //建立连接
        ws.onopen = () => {
            // 建立连接
            ws.send('something');
        };

        //接受消息
        ws.onmessage = (e) => {
            // 收到了消息
            if (e.data == '-1') {
                //提示用户消息
                AlertIOS.alert(
                    '温馨提示',
                    '您的账号已被管理员强制离线.'
                );
                Key.username = '';
                AsyncStorage.clear();
                this.props.navigator.push({
                    id: 'LoginPage'
                });
            }else if(e.data=='-2'){
                //提示用户信息
                AlertIOS.alert(
                    '温馨提示',
                    '您的账号已在其他设备登录.'
                );
                Key.username = '';
                AsyncStorage.clear();
                this.props.navigator.push({
                    id: 'LoginPage'
                });
            }
        };

    }
    onPress() {
        let that = this;
        let userValue = this.refs.main.refs.form.getValue();
        if (userValue) {
            this.setState({
                value: userValue
            });
            const userName = userValue.username;
            const userPwd = userValue.password;
            Utils.transport(URL.login, {
                username: userName,
                password: userPwd
            }, function (data) {
                if (data >= 0) {
                    //登陆成功!
                    that.setState({
                        options: tcomb.update(that.state.options, {
                            fields: {
                                username: {
                                    hasError: {'$set': false}
                                },
                                password: {
                                    hasError: {'$set': false}
                                }
                            }
                        })
                    });
                    AlertIOS.alert(
                        '免责声明',
                        '本软件开发者为个人，软件中的内容均为研究学习之用，不作为推荐或买卖依据，参考软件造成的盈利与亏损均与开发者,发布者无关，造成的一切后果均由自己承担，继续使用视为遵守本原则。',
                        [
                            {
                                text: '继续', onPress: () => {
                                Key.username = userName;
                                AsyncStorage.multiSet([
                                    ['username', userName],
                                    ['password', userPwd],
                                    ['deviceid', DeviceInfo.getUniqueID()],
                                    ['userType', data.toString()]
                                ], ()=> {
                                    that._openWs();
                                    that.props.navigator.push({
                                        id: 'Main'
                                    });
                                });
                            }
                            },
                            {text: '放弃', onPress: () => console.log('Bar Pressed!')}
                        ]
                    )
                } else if (data == -1) {
                    that.setState({
                        options: tcomb.update(that.state.options, {
                            fields: {
                                username: {
                                    hasError: {'$set': true}
                                },
                                password: {
                                    hasError: {'$set': true}
                                }
                            }
                        })
                    });
                } else if (data == -2) {
                    AlertIOS.alert(
                        '温馨提示',
                        '您的账户已超期.'
                    );
                }
            });
        }
    }

    _visitorPost() {
        const VISITOR = URL.local + 'youke';
        let that = this;
        Utils.transport(VISITOR, '', function (data) {
            if (data) {
                Utils.transport1(URL.local + 'youkeend',{}, function (result) {
                    AlertIOS.alert(
                        '免责声明',
                        '本软件开发者为个人，软件中的内容均为研究学习之用，不作为推荐或者买卖，参考软件造成的盈利与亏损均于开发者，发布者无关，造成的一切后果均由自己承担，继续使用视为遵守本原则。',
                        [
                            {
                                text: '继续', onPress: () => {
                                AsyncStorage.setItem('userType', '0', ()=> {
                                    AlertIOS.alert(
                                        '温馨提示',
                                        result
                                    );
                                    that.props.navigator.push({
                                        id: 'Main',
                                        message: 'visitor'
                                    })
                                })
                            }
                            },
                            {text: '放弃', onPress: () => console.log('Bar Pressed!')}
                        ]
                    )
                })

            } else {
                AlertIOS.alert(
                    '温馨提示',
                    '您的账户已超期.'
                );
            }
        })
    }

    onPress_visitor() {
        this._visitorPost();


    }

    onReg() {
        const REG_ALLOW = URL.local + 'registmode';
        let that = this;
        Utils.get(REG_ALLOW, function (data) {
            if (data) {
                that.props.navigator.push({
                    id: 'Register'
                });
            } else {
                AlertIOS.alert(
                    '温馨提示',
                    '注册功能暂时关闭.'
                )
            }
        })

    }

    findPwd() {
        this.props.navigator.push({
            id: 'FindPwd',
            name: '找回密码'
        });
    }

    renderScene(route, navigator) {
        return (
            <View style={styles.container}>
                <Image
                    style={styles.logo}
                    source={require('../image/logo.png')}
                />
                <Text style={styles.title}>
                    神秘涨停网
                </Text>
                <Form

                    ref='form'
                    type={User}
                    options={this.state.options}
                    value={this.state.value}
                />
                <TouchableHighlight style={styles.button} onPress={this.onPress.bind(this)} underlayColor='#e02820'>
                    <Text style={styles.buttonText}>马上登录</Text>
                </TouchableHighlight>
                <TouchableHighlight style={styles.button} onPress={this.onPress_visitor.bind(this)}
                                    underlayColor='#e02820'>
                    <Text style={styles.buttonText}>游客登录</Text>
                </TouchableHighlight>
                <View style={styles.rfText}>
                    <Text style={styles.registerText} onPress={this.onReg.bind(this)}>立即注册</Text>
                    <Text style={styles.findPwdText} onPress={this.findPwd.bind(this)}>找回密码</Text>
                </View>
                {/*<Text style={styles.p}>
                 官网:{'\n'}www.smztw.com {'\n'}www.95889588.com.cn
                 </Text>*/}
            </View>
        );
    }

    render() {
        return (
            <Navigator
                ref='main'
                message={this.props.message}
                renderScene={this.renderScene.bind(this)}
                navigationBar={
                    <Navigator.NavigationBar
                        style={{backgroundColor: '#e02820', alignItems: 'center'}}
                        routeMapper={NavigationBarRouteMapper} />
                }/>
        );
    }
}

const styles = StyleSheet.create({
    Index: {
        flex: 1
    },
    container: {
        flex:1,
        marginTop: 50,
        justifyContent: 'center',
        padding: 20,
        backgroundColor: '#ffffff'
    },
    logo: {
        flex: 1,
        alignSelf: 'center',
        marginTop: 20,
        width: 150,
        resizeMode: Image.resizeMode.contain
    },
    title: {
        fontSize: 25,
        alignSelf: 'center',
        marginBottom: 15,
        marginTop: 15
    },
    buttonText: {
        fontSize: 18,
        color: 'white',
        alignSelf: 'center'
    },
    button: {
        height: 36,
        backgroundColor: '#e02820',
        borderColor: '#e02820',
        borderWidth: 1,
        borderRadius: 8,
        marginBottom: 10,
        alignSelf: 'stretch',
        justifyContent: 'center'
    },
    findPwdText: {
        flex: 1,
        fontSize: 15,
        textDecorationLine: 'underline',
        textAlign: 'right'
    },
    rfText: {
        flex: 1,
        flexDirection: 'row'
    },
    registerText: {
        flex: 1,
        fontSize: 15,
        textDecorationLine: 'underline',
        textAlign: 'left'
    },
    p: {
        position:'absolute',
        width:Utils.size.width,
        bottom:0,
        textAlign:'center',
        fontSize: 15,
        lineHeight: 20,
        color: "#e02820"
    }
});